package com.sporadic.wx.controller;

import com.alibaba.fastjson.JSONObject;
import com.sporadic.wx.service.WxAuthentication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/wx")
public class WxLittleLogin {
    @Autowired
    private WxAuthentication wxAuthentication;
    @GetMapping("/login")
    public ResponseEntity<Map<String,Object>> login(String wxcode) {
        log.info("wx-code:"+wxcode);
        JSONObject resultValue = wxAuthentication.getSessionKeyOrOpenId(wxcode);
       log.info("--->>>>>"+resultValue);
        String openid = resultValue.getString("openid" );
        String sessionKey = resultValue.getString( "session_key" );
        Map<String,Object> map=new HashMap<>();
        map.put("session_key",sessionKey);
        map.put("openid",openid);
        return ResponseEntity.ok(map);

    }

    @GetMapping("/jm")
    public ResponseEntity<String> jm(String encrypData, String ivData, String sessionKey){
        try {
            String decrypt = wxAuthentication.decrypt(sessionKey, ivData, encrypData);
            return ResponseEntity.ok(decrypt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
